//
//  YZESignupProfileTableViewController.m
//  yilutongxing
//
//  Created by T&J on 2017/3/31.
//  Copyright © 2017年 YZE. All rights reserved.
//

#import "YZESignupProfileTableViewController.h"
#import <QMUIKit/QMUIKit.h>
#import "CommonDefine.h"
#import <GTMBase64.h>
#import "YZEUserinfoTFViewController.h"
#import "IQActionSheetPickerView.h"
#import <ActionSheetCustomPicker.h>
#import <ActionSheetDatePicker.h>
#import <MJExtension.h>
#import "DataUtils.h"
#import "functions.h"

#define GraftingsURL @"/api/graftings"
#define URL_DistrictsTree @"/api/districtsTree"
#define URL_GetAllhospitals @"/api/commonhospitals?page=0&size=10000"
#define URL_ActivateAccount @"/api/users/sickperson/acitvited?acitvationCode="

@interface YZESignupProfileTableViewController ()<NetworkUtilsDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate,IQActionSheetPickerViewDelegate,ActionSheetCustomPickerDelegate>
@property (nonatomic, strong) QMUIFillButton *m_btn_finish;
@property (weak, nonatomic) IBOutlet UIImageView *headImageView;

@property(nonatomic,strong)UIImage *image;//头像
@property(nonatomic,copy)NSString *hospitolID; //医院
@property(nonatomic,copy)NSString *name;       //姓名
@property(nonatomic,copy)NSString *address;//地址
@property(nonatomic,copy)NSString *gender;//性别
@property(nonatomic,copy)NSString *avatar;//头像
@property(nonatomic,copy)NSString *casenumber; //病例号
@property(nonatomic,copy)NSString *districtId;  //地区ID
@property(nonatomic,copy)NSString *graftingId; //移植类型
@property(nonatomic,copy)NSString *idcard;  //ID
@property(nonatomic,copy)NSString *medicalnumber;  //诊卡号
@property(nonatomic,copy)NSString *birthday;  //生日
@property(nonatomic,assign)NSIndexPath *tempIndexPath;

@property (nonatomic, strong) NSMutableArray *grafthingArr;
@property (nonatomic, strong) NSMutableArray *grafthingIDArr;

@property (nonatomic, strong) NSMutableArray *hospitolArr;
@property (nonatomic, strong) NSMutableArray *hospitolIDArr;

@property (nonatomic,strong) NSArray *cityArr; // 解析出来的最外层数组
@property (nonatomic,strong) NSArray *provinceArr; // 省
@property (nonatomic,strong) NSArray *countryArr; // 市
@property (nonatomic,strong) NSArray *districtArr; // 区
@property (nonatomic,strong) NSMutableArray *districtArr1;
@property (nonatomic,strong) NSMutableArray *districtIDArr;
@property (nonatomic,assign) NSInteger index1; // 省下标
@property (nonatomic,assign) NSInteger index2; // 市下标
@property (nonatomic,assign) NSInteger index3; // 区下标
@property (nonatomic,strong) ActionSheetCustomPicker *city_picker; // 选择器

@property(nonatomic,strong)NSMutableArray *array;
@property (nonatomic,strong) NSArray *selections; //!< 选择的三个下标

@end

@implementation YZESignupProfileTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = NO;
    self.navigationItem.title = @"完善资料";
    self.headImageView.layer.masksToBounds=YES;
    self.headImageView.layer.cornerRadius=22;
    self.grafthingArr=[NSMutableArray array];
    self.grafthingIDArr=[NSMutableArray array];
    self.hospitolArr=[NSMutableArray array];
    self.hospitolIDArr=[NSMutableArray array];
    
    //获取所有移植类型
    [[YZENetwork sharedInstace]getRequestWithUrl:[BASE stringByAppendingString:GraftingsURL] parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
        NSArray *arr = [BaseModel mj_keyValuesArrayWithObjectArrayAdd:responseObject];
        for (NSDictionary *base in arr) {
            [self.grafthingArr addObject:base[@"name"]];
            [self.grafthingIDArr addObject:base[@"id"]];
        }
        
    }];
    
    [[YZENetwork sharedInstace]getRequestWithUrl:[BASE stringByAppendingString:URL_GetAllhospitals] parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
        NSArray *arr=[BaseModel mj_objectArrayWithKeyValuesArrayAdd:responseObject[@"all"]];
        for (BaseModel *base in arr) {
            if([base.name isEqualToString:@"广州军区广州总医院"]){
                [self.hospitolArr insertObject:base.name atIndex:0];
                [self.hospitolIDArr insertObject:base.ID atIndex:0];
            }
            else if ([functions ishaveGZJQLitteral:base.name]) {
                [self.hospitolArr insertObject:base.name atIndex:1];
                [self.hospitolIDArr insertObject:base.ID atIndex:1];
            }
            else {
                [self.hospitolArr addObject:base.name];
                [self.hospitolIDArr addObject:base.ID];
            }
        }
    }];
    
    [self getDistrictData];
}
//加载城市json
- (void)loadFirstData
{
    self.cityArr = self.array;
    
    NSMutableArray *firstName = [[NSMutableArray alloc] init];
    for (NSDictionary *dict in self.cityArr)
    {
        NSString *name = dict[@"provinceName"];
        [firstName addObject:name];
    }
    // 第一层是省份 分解出整个省份数组
    self.provinceArr = firstName;
}

// 根据传进来的下标数组计算对应的三个数组，一定要先加载出这三个数组，不然就蹦了
- (void)calculateFirstData
{
    // 拿出省的数组
    [self loadFirstData];
    
    NSMutableArray *cityNameArr = [[NSMutableArray alloc] init];
    // 根据省的index1，默认是0，拿出对应省下面的市
    for (NSDictionary *cityName in self.cityArr[self.index1][@"citys"]) {
        
        NSString *name1 = cityName[@"cityName"];
        [cityNameArr addObject:name1];
    }
    // 组装对应省下面的市
    self.countryArr = cityNameArr;
    // index1对应省的字典、市的数组，index2市的字典、对应市的数组
    self.districtArr = self.cityArr[self.index1][@"citys"][self.index2][@"districts"];;
    [self.districtArr1 removeAllObjects];
    [self.districtIDArr removeAllObjects];
    for (NSDictionary *dic in self.districtArr) {
        
        [self.districtArr1 addObject:dic[@"districtName"]];
        [self.districtIDArr addObject:dic[@"districtID"]];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 11;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return FOOTER_HEIGHT;
}

//footer完成按钮
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *rowview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, FOOTER_HEIGHT)];
    _m_btn_finish = [[QMUIFillButton alloc] initWithFillType:QMUIFillButtonColorBlue];
    [self.m_btn_finish setTitle:@"完成" forState:UIControlStateNormal];
    [self.m_btn_finish setFrame:CGRectMake((SCREEN_WIDTH-BTN_ROW_WIDTH)/2, (FOOTER_HEIGHT-BTN_ROW_HEIGHT)/2, BTN_ROW_WIDTH, BTN_ROW_HEIGHT)];
    [self.m_btn_finish addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
    [rowview addSubview:self.m_btn_finish];
    if (section!=0) {
        return nil;
    }
    return rowview;
}
-(void)saveClick{
    
    if ([self.name isNotEmpty]&&
        [self.gender isNotEmpty]&&
        [self.hospitolID isNotEmpty]&&
        [self.districtId isNotEmpty]&&
        [self.address isNotEmpty]&&
        [self.birthday isNotEmpty]&&
        [self.casenumber isNotEmpty]&&
        [self.graftingId isNotEmpty]&&
        [self.idcard isNotEmpty]&&
        [self.medicalnumber isNotEmpty]) {
        
        NSData *raw_data = UIImageJPEGRepresentation(self.image, 1.0f);
        NSData *encoded_data = [GTMBase64 encodeData:raw_data];
        self.avatar = [[NSString alloc]initWithData:encoded_data encoding:NSASCIIStringEncoding];
        
        NSDictionary *dic=@{@"name":self.name,
                            @"avatar":self.avatar,
                            @"gender":self.gender,
                            @"hospitalId":self.hospitolID,
                            @"districtId":self.districtId,
                            @"address":self.address,
                            @"birthday":self.birthday,
                            @"casenumber":self.casenumber,
                            @"graftingId":self.graftingId,
                            @"idcard":self.idcard,
                            @"medicalnumber":self.medicalnumber,};
        
        
        NSString *URLpath=[NSString stringWithFormat:@"%@%@%@", BASE, URL_ActivateAccount, self.acitvationCode];
        
        [[YZENetwork sharedInstace]putRequestWithUrl:URLpath parameters:dic delegate:self requestTag:1 successBlock:^(id responseObject) {
            [QMUITips hideAllToastInView:self.view animated:YES];
            [QMUITips showInfo:@"已保存" inView:self.view hideAfterDelay:2.5];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
        [QMUITips showLoadingInView:self.view];
    }
    else{
        [UIView showToastWindowWithMessage:@"请完善信息"];
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UIStoryboard *storyboard=[UIStoryboard storyboardWithName:@"userinfo" bundle:nil];
    UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
    UIView *vi=[[UIView alloc]init];
    vi.backgroundColor=[UIColor clearColor];
    cell.selectedBackgroundView=vi;
    self.tempIndexPath=indexPath;
    
    YZEUserinfoTFViewController *info=[storyboard instantiateViewControllerWithIdentifier:@"TFInput"];
    switch (indexPath.row) {
        case 0:
            [self changeImage];
            break;
        case 1:{
            info.type=@"姓名";
            info.block=^(NSString* str){
                cell.detailTextLabel.text=str;
                self.name=str;
            };
            [self.navigationController pushViewController:info animated:YES];
            
        }
            break;
        case 2:{
            IQActionSheetPickerView *picker = [[IQActionSheetPickerView alloc] initWithTitle:@"" delegate:self];
            picker.titleFont = [UIFont systemFontOfSize:12];
            picker.titleColor = [UIColor redColor];
            [picker setTag:1];
            [picker setTitlesForComponents:@[self.grafthingArr]];
            [picker show];
        }
            break;
        case 3:{
            UIAlertController *Alert=[UIAlertController alertControllerWithTitle:@"请选择性别" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            
            UIAlertAction *action1=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            UIAlertAction  *action2=[UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                cell.detailTextLabel.text=@"男";
                self.gender=@"MALE";
                [self.tableView reloadData];
            }];
            UIAlertAction *action3=[UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                cell.detailTextLabel.text=@"女";
                self.gender=@"FEMALE";
                [self.tableView reloadData];
            }];
            //3.将按键添加到警告框中
            [Alert addAction:action1];
            [Alert addAction:action2];
            [Alert addAction:action3];
            
            //将警告呈现处理
            [self presentViewController:Alert animated:YES completion:nil];
            
        }
            break;
        case 4:
        {
            IQActionSheetPickerView *picker = [[IQActionSheetPickerView alloc] initWithTitle:@"Date Picker" delegate:self];
            [picker setActionSheetPickerStyle:IQActionSheetPickerStyleDatePicker];
            [picker setTag:2];
            [picker show];
            
        }
            break;
        case 5:{
            info.type=@"身份证号码";
            info.block=^(NSString* str){
                cell.detailTextLabel.text=str;
                self.idcard=str;
            };
            [self.navigationController pushViewController:info animated:YES];
            
        }
            break;
        case 6:{
            IQActionSheetPickerView *picker = [[IQActionSheetPickerView alloc] initWithTitle:@"" delegate:self];
            picker.titleFont = [UIFont systemFontOfSize:12];
            picker.titleColor = [UIColor redColor];
            [picker setTag:3];
            [picker setTitlesForComponents:@[self.hospitolArr]];
            [picker show];
        }
            break;
        case 7:{
            info.type=@"病历号";
            info.block=^(NSString* str){
                cell.detailTextLabel.text=str;
                self.casenumber=str;
            };
            [self.navigationController pushViewController:info animated:YES];
        }
            break;
            
        case 8:{
            info.type=@"诊卡号";
            info.block=^(NSString* str){
                cell.detailTextLabel.text=str;
                self.medicalnumber=str;
            };
            [self.navigationController pushViewController:info animated:YES];
        }
            break;
        case 9:{
            self.city_picker = [[ActionSheetCustomPicker alloc]initWithTitle:@"选择地区" delegate:self showCancelButton:YES origin:self.view initialSelections:@[@(self.index1),@(self.index2),@(self.index3)]];
            self.city_picker.tapDismissAction  = TapActionSuccess;
            self.city_picker.tag = ROWINDEX(indexPath);
            // 可以自定义左边和右边的按钮
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            button.frame = CGRectMake(0, 0, 44, 44);
            [button setTitle:@"取消" forState:UIControlStateNormal];
            
            UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
            [button1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            button1.frame = CGRectMake(0, 0, 44, 44);
            [button1 setTitle:@"确定" forState:UIControlStateNormal];
            [self.city_picker setCancelButton:[[UIBarButtonItem alloc] initWithCustomView:button]];
            [self.city_picker setDoneButton:[[UIBarButtonItem alloc] initWithCustomView:button1]];
            
            [self.city_picker showActionSheetPicker];
            
            
        }
            break;
            
        case 10:{
            info.type=@"地址";
            info.block=^(NSString* str){
                cell.detailTextLabel.text=str;
                self.address=str;
            };
            [self.navigationController pushViewController:info animated:YES];
        }
            break;
    }
    
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return YES;
}

-(BOOL)shouldAutorotate
{
    return YES;
}


-(void)actionSheetPickerView:(IQActionSheetPickerView *)pickerView didSelectDate:(NSDate *)date
{
    UITableViewCell *cell=[self.tableView cellForRowAtIndexPath:self.tempIndexPath];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterNoStyle];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    cell.detailTextLabel.text=[formatter stringFromDate:date];
    self.birthday=cell.detailTextLabel.text;
    [self.tableView reloadData];
    
}

-(void)actionSheetPickerView:(IQActionSheetPickerView *)pickerView didSelectTitles:(NSArray *)titles
{
    UITableViewCell *cell=[self.tableView cellForRowAtIndexPath:self.tempIndexPath];
    
    switch (pickerView.tag)
    {
        case 1:
            cell.detailTextLabel.text=[titles componentsJoinedByString:@""];
            
            self.graftingId=self.grafthingIDArr[[self.grafthingArr indexOfObject:cell.detailTextLabel.text]];
            break;
            
        case 3:
            cell.detailTextLabel.text=[titles componentsJoinedByString:@""];
            self.hospitolID=self.hospitolIDArr[[self.hospitolArr indexOfObject:cell.detailTextLabel.text]];
            break;
            
    }
    [self.tableView reloadData];
}



//点击头像进入相册事件
-(void)changeImage{
    UIImagePickerController *vc = [UIImagePickerController new];
    vc.delegate = self;
    vc.allowsEditing = YES;
    [self presentViewController:vc animated:YES completion:nil];
}
#pragma mark 选择图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *image = info[UIImagePickerControllerEditedImage];
    self.headImageView.image=image;
    self.image=image;
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark 地区选择相关
- (void)getDistrictData{
    //设置选择器
    if (self.selections.count) {
        self.index1 = [self.selections[0] integerValue];
        self.index2 = [self.selections[1] integerValue];
        self.index3 = [self.selections[2] integerValue];
    }
    if ([DataUtils fileIfExists:DISTRICTREE_PLISTNAME]) {
        self.array = [[NSMutableArray alloc]initWithContentsOfFile:[[DataUtils getDocumentsPath] stringByAppendingPathComponent:DISTRICTREE_PLISTNAME]];
        [self calculateFirstData];
    }
    else {
        [[YZENetwork sharedInstace]getRequestWithUrl:[BASE stringByAppendingString:URL_DistrictsTree] parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
            self.array=responseObject;
            [self calculateFirstData];
        }];
    }
}
#pragma mark UIPickerViewDelegate Implementation

#pragma mark - UIPickerViewDataSource Implementation
//返回pickerview列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}
//返回pickerview某列行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    // Returns
    switch (component)
    {
        case 0: return self.provinceArr.count;
        case 1: return self.countryArr.count;
        case 2:return self.districtArr1.count;
        default:break;
    }
    return 0;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    switch (component)
    {
        case 0: return self.provinceArr[row];break;
        case 1: return self.countryArr[row];break;
        case 2:return self.districtArr1[row];break;
        default:break;
    }
    return nil;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel* label = (UILabel*)view;
    if (!label)
    {
        label = [[UILabel alloc] init];
        [label setFont:[UIFont systemFontOfSize:14]];
    }
    
    NSString * title = @"";
    switch (component)
    {
        case 0: title =   self.provinceArr[row];break;
        case 1: title =   self.countryArr[row];break;
        case 2: title =   self.districtArr1[row];break;
        default:break;
    }
    label.textAlignment = NSTextAlignmentCenter;
    label.text=title;
    return label;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    switch (component)
    {
        case 0:
        {
            self.index1 = row;
            self.index2 = 0;
            self.index3 = 0;
            //            [self calculateData];
            // 滚动的时候都要进行一次数组的刷新
            [self calculateFirstData];
            [pickerView reloadComponent:1];
            [pickerView reloadComponent:2];
            [pickerView selectRow:0 inComponent:1 animated:YES];
            [pickerView selectRow:0 inComponent:2 animated:YES];
        }
            break;
            
        case 1:
        {
            self.index2 = row;
            self.index3 = 0;
            //            [self calculateData];
            [self calculateFirstData];
            [pickerView selectRow:0 inComponent:2 animated:YES];
            [pickerView reloadComponent:2];
        }
            break;
        case 2:
            self.index3 = row;
            break;
        default:break;
    }
}

- (void)configurePickerView:(UIPickerView *)pickerView
{
    pickerView.showsSelectionIndicator = NO;
}
// 点击done的时候回调
- (void)actionSheetPickerDidSucceed:(ActionSheetCustomPicker *)actionSheetPicker origin:(id)origin
{
    NSMutableString *detailAddress = [[NSMutableString alloc] init];
    if (self.index1 < self.provinceArr.count) {
        NSString *firstAddress = self.provinceArr[self.index1];
        [detailAddress appendString:firstAddress];
    }
    if (self.index2 < self.countryArr.count) {
        NSString *secondAddress = self.countryArr[self.index2];
        [detailAddress appendString:secondAddress];
    }
    if (self.index3 < self.districtArr1.count) {
        NSString *thirfAddress = self.districtArr1[self.index3];
        [detailAddress appendString:thirfAddress];
        
        self.districtId=self.districtIDArr[self.index3];
    }
    // 此界面显示
    UITableViewCell *c = [self.tableView cellForRowAtIndexPath:DEROWINDEX(self.city_picker.tag)];
    c.detailTextLabel.text = detailAddress;
    [self.tableView reloadData];
    // 回调到上一个界面
    
}

#pragma mark - 网络代理
- (void)OnStartWithRequestTag:(int)tag{}
- (void)OnFinishWithRequestTag:(int)tag{}
- (void)OnSuccess:(id)responseObject requestTag:(int)tag{}
- (void)OnFail:(NSString *)errorMsg errorCode:(NSInteger)errorCode requestTag:(int)tag{
    [QMUITips hideAllToastInView:self.view animated:YES];
    [QMUITips showError:errorMsg inView:self.view hideAfterDelay:2.5];
}

#pragma mark - 数据配置
- (NSArray *)provinceArr
{
    if (_provinceArr == nil) {
        _provinceArr = [[NSArray alloc] init];
    }
    return _provinceArr;
}
-(NSArray *)countryArr
{
    if(_countryArr == nil)
    {
        _countryArr = [[NSArray alloc] init];
    }
    return _countryArr;
}

- (NSArray *)districtArr
{
    if (_districtArr == nil) {
        _districtArr = [[NSArray alloc] init];
    }
    return _districtArr;
}
- (NSMutableArray *)districtArr1
{
    if (_districtArr1 == nil) {
        _districtArr1 = [[NSMutableArray alloc] init];
    }
    return _districtArr1;
}
- (NSMutableArray *)districtIDArr
{
    if (_districtIDArr == nil) {
        _districtIDArr = [[NSMutableArray alloc] init];
    }
    return _districtIDArr;
}
-(NSArray *)cityArr
{
    if (_cityArr == nil) {
        _cityArr = [[NSArray alloc] init];
    }
    return _cityArr;
}

@end
